import type { Router } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { useUserStore } from '@/store';
import { isLogin } from '@/utils/auth';
import useUser from '@/hooks/user';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    const { user } = userStore;
    const { jumpFirstPage, jumpLoginPage } = useUser();
    if (isLogin()) {
      if (user?.id) {
        jumpFirstPage(to, next);
      } else {
        try {
          await userStore.info();
          jumpFirstPage(to, next);
        } catch (error) {
          await userStore.logout();
          jumpLoginPage(to, next);
        }
      }
    } else {
      if (to.name === 'SignUpInfo') {
        next();
        return;
      }
      jumpLoginPage(to, next);
    }
  });
}
